package cn.zshprint.serein.config;

import com.alibaba.fastjson.JSON;
import org.springframework.data.elasticsearch.core.DefaultEntityMapper;
import org.springframework.data.elasticsearch.core.DefaultResultMapper;
import org.springframework.data.elasticsearch.core.mapping.ElasticsearchPersistentEntity;
import org.springframework.data.elasticsearch.core.mapping.ElasticsearchPersistentProperty;
import org.springframework.data.mapping.context.MappingContext;
import org.springframework.util.StringUtils;

/**
 * @Description: 自定义接收结果集的转换方式
 * @Author: Jonas
 * @Date: 2020-04-16 11:30
 */
public class MyResultMapper extends DefaultResultMapper {

    private MappingContext<? extends ElasticsearchPersistentEntity<?>, ElasticsearchPersistentProperty> mappingContext;

    public MyResultMapper(MappingContext<? extends ElasticsearchPersistentEntity<?>, ElasticsearchPersistentProperty> mappingContext){
        super(new DefaultEntityMapper(mappingContext));
        this.mappingContext = mappingContext;
    }

    @Override
    public <T> T mapEntity(String source, Class<T> clazz) {
        if (StringUtils.isEmpty(source)) {
            return null;
        }
        try {
            // 这里使用fastjson进行数据格式化，将其转换为驼峰格式的数据
            return JSON.parseObject(source, clazz);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
